import React from 'react';
import { Card, Table, Tag, Typography, Spin, Empty } from 'antd';
import { HistoryOutlined, CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import { useUserWebSocket } from '../contexts/UserWebSocketContext';
import type { AccessLog } from '../contexts/UserWebSocketContext';

const { Title, Text } = Typography;

const MyAccessLogs: React.FC = () => {
    const { logs, isConnected } = useUserWebSocket();

    const columns: ColumnsType<AccessLog> = [
        {
            title: '时间',
            dataIndex: 'timestamp',
            key: 'timestamp',
            width: 180,
            render: (timestamp) => (
                <div>
                    <div>{dayjs(timestamp).format('YYYY-MM-DD')}</div>
                    <Text type="secondary" style={{ fontSize: '12px' }}>
                        {dayjs(timestamp).format('HH:mm:ss')}
                    </Text>
                </div>
            ),
            sorter: (a, b) => dayjs(a.timestamp).unix() - dayjs(b.timestamp).unix(),
            defaultSortOrder: 'descend',
        },
        {
            title: '设备',
            dataIndex: 'device',
            key: 'device',
        },
        {
            title: '状态',
            dataIndex: 'is_success',
            key: 'is_success',
            render: (isSuccess: boolean) => (
                isSuccess ? (
                    <Tag color="success" icon={<CheckCircleOutlined />}>成功</Tag>
                ) : (
                    <Tag color="error" icon={<CloseCircleOutlined />}>失败</Tag>
                )
            ),
        },
    ];

    if (!isConnected && logs.length === 0) {
        return (
            <div style={{ textAlign: 'center', padding: '50px' }}>
                <Spin size="large" />
                <p style={{ marginTop: '20px' }}>正在连接实时日志服务...</p>
            </div>
        );
    }

    return (
        <Card>
            <Title level={4} style={{ marginBottom: '20px' }}>
                <HistoryOutlined style={{ marginRight: '10px' }} />
                我的访问记录
            </Title>
            <Table
                columns={columns}
                dataSource={logs}
                rowKey="id"
                loading={!isConnected}
                pagination={{
                    pageSize: 10,
                    showTotal: (total) => `共 ${total} 条记录`,
                    showSizeChanger: true,
                    pageSizeOptions: ['10', '20', '50'],
                    showQuickJumper: true,
                }}
                scroll={{ y: '60vh' }}
                locale={{
                    emptyText: (
                        <Empty
                            image={Empty.PRESENTED_IMAGE_SIMPLE}
                            description="暂无访问记录"
                        />
                    )
                }}
            />
        </Card>
    );
};

export default MyAccessLogs;